package com.deke.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deke.entity.AclPermission;
import com.deke.entity.AclRolePermission;
import com.deke.security.utils.WebUtils;
import com.deke.system.dao.AclPermissionDao;
import com.deke.system.service.AclPermissionService;
import com.deke.system.service.AclRolePermissionService;
import com.deke.system.vo.FenPermissionVo;
import com.deke.system.vo.PermissionVo;
import com.deke.utils.ListPage;
import com.deke.vo.PageVo;
import com.deke.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/12/1 19:20
 * @description：
 * @modified By：
 * @version:
 **/

@Service
public class AclPermissionServiceImpl implements AclPermissionService {
    @Autowired
    private AclPermissionDao permissionDao;

    @Autowired
    private AclRolePermissionService rolePermissionService;

    @Override
    public List<AclPermission> queryPermissionByUserid(String userid) {
        List<AclPermission> permissions = permissionDao.queryPermissionByUserid(userid);
        return permissions;
    }

    @Override
    public Result<List<AclPermission>> queryPermissionByUsername() {
        String username = WebUtils.getUsername();
        List<AclPermission> permissions = permissionDao.queryPermissionByUsername(username);
        //筛选一级菜单
        List<AclPermission> first = new ArrayList<>();
        String pid = "1";
        for (AclPermission permission : permissions) {
            if (permission.getPid().equals(pid)){
                first.add(permission);
            }
        }
        System.out.println(first);
        for (AclPermission f : first) {
            f.setChildren(findChildren(permissions,f.getId()));
        }
        return new Result<>(2000,"查询菜单",first);
    }

    /**
     * @create by: Username 刘亦辰 
     * @description: 角色管理 通过角色id查询权限
     * @create time: 2022/12/6 17:07
     * @param null
     * @return :  
     **/
    //本地事务锁
    @Transactional
    @Override
    public Result<Map<String, Object>> findPermissionByRoleId(String roleId) {
        //查询所有的权限
        List<AclPermission> allPermissions = permissionDao.selectList(null);
        List<AclPermission> frist = new ArrayList<>();
        for (AclPermission p : allPermissions) {
            if (p.getPid().equals("1")){
                frist.add(p);
            }
        }

        for (AclPermission f : frist) {
            f.setChildren(findChildren(allPermissions,f.getId()));
        }
        //查询用户具有的权限
        List<String> rolePermissionIds = permissionDao.findPermissionIdByRoleId(roleId);
        System.out.println(rolePermissionIds);
        Map map = new HashMap();
        map.put("allPermissions",frist);
        map.put("checkItems",rolePermissionIds);
        return new Result<>(2000,"查询成功",map);
    }


    /**
     * @create by: Username 刘亦辰 
     * @description: 角色管理  分配权限 
     * @create time: 2022/12/6 18:07
     * @param roleId
     * @return : com.deke.vo.Result<java.util.Map<java.lang.String,java.lang.Object>> 
     **/
    @Transactional
    @Override
    public Result confirmFenPermission(FenPermissionVo fenPermissionVo) {
        //删除角色原有的权限
        boolean b = permissionDao.deletePermissionByRoleId(fenPermissionVo.getRoleId());
        //添加角色权限
        List<String> permissionIds = fenPermissionVo.getPermissionIds();
        System.out.println(permissionIds);
        List<AclRolePermission> rolePermissionList = new ArrayList<>();
        for (String p : permissionIds) {
            AclRolePermission rolePermission = new AclRolePermission(fenPermissionVo.getRoleId(), p, 0, LocalDateTime.now(), LocalDateTime.now() );
            rolePermissionList.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissionList);
        return new Result(2000,"分配成功");
    }


    /**
     * @create by: Username 刘亦辰 
     * @description: 菜单管理  条件查询 
     * @create time: 2022/12/6 18:41
     * @param null
     * @return :  
     **/
    @Transactional
    @Override
    public Result queryByConditionPage(Integer currentPage, Integer pageSize, PermissionVo permissionVo) {

        Page<AclPermission> page = new Page<>(currentPage,pageSize);
        QueryWrapper<AclPermission> wrapper = new QueryWrapper<>();
        List<AclPermission> records = new ArrayList<>();
        Page<AclPermission> list = new Page<>();

        if (StringUtils.hasText(permissionVo.getName())){
            wrapper.like("name",permissionVo.getName());
            Page<AclPermission> res = permissionDao.selectPage(page, wrapper);
            records = res.getRecords();
        }else {
            wrapper.eq("pid","1");
            list = permissionDao.selectPage(page,wrapper);
            List<AclPermission> permissions = permissionDao.selectList(null);
            for (AclPermission p : permissions) {
                if (p.getPid().equals("1")){
                    records.add(p);
                }
            }
            for (AclPermission record : records) {
                record.setChildren(findChildren(permissions,record.getId()));
            }
        }

        PageVo pageVo = ListPage.startPage(records, currentPage, pageSize);
        return new Result(2000,"查询成功",pageVo);
    }


    /**
     * @create by: Username 刘亦辰 
     * @description: 菜单管理  添加通用
     * @create time: 2022/12/6 21:20
     * @param null
     * @return :  
     **/
    @Override
    public Result insert(PermissionVo permissionVo) {
        AclPermission permission = new AclPermission();
        System.out.println(permissionVo.getType());
        if (permissionVo.getType().equals("1")){
            permission.setType(1);
        }else {
            permission.setType(2);
        }
        permission.setPid(permissionVo.getPid());
        permission.setName(permissionVo.getName());
        permission.setPermissionValue(permissionVo.getPermissionValue());
        permission.setPath(permissionVo.getPath());
        permission.setIcon(permissionVo.getIcon());
        permission.setIsDeleted(0);
        permission.setGmtCreate(LocalDateTime.now());
        permission.setGmtModified(LocalDateTime.now());
        int insert = permissionDao.insert(permission);
        if (insert>0){
            return  new Result(2000,"添加成功");
        }
        return new Result(0000,"添加失败");
    }


    /**
     * @create by: Username 刘亦辰 
     * @description: 菜单管理  修改信息
     * @create time: 2022/12/6 21:40
     * @param null
     * @return :  
     **/
    @Override
    public Result update(AclPermission aclPermission) {
        int update = permissionDao.updateById(aclPermission);
        if (update>0){
            return new Result(2000,"修改成功");
        }
        return new Result(0000,"修改失败");
    }



    /**
     * @create by: Username 刘亦辰 
     * @description: 菜单管理 删除 
     * @create time: 2023/2/12 12:04
     * @param null
     * @return :  
     **/
    @Override
    public Result deleteById(List idList) {
        int i = permissionDao.deleteBatchIds(idList);
        if (i > 0){
            return new Result(2000,"删除成功",null);
        }
        return new Result(0000,"删除失败",null);
    }


    /**
     * @create by: Username 刘亦辰 
     * @description: 递归查询权限方法 
     * @create time: 2022/12/6 17:08
     * @param null
     * @return :  
     **/
    private List<AclPermission> findChildren(List<AclPermission> permissions, String id) {
        List<AclPermission> serconds = new ArrayList<>();
        for (AclPermission p : permissions) {
            if (p.getPid().equals(id)){
                serconds.add(p);
            }
        }

        for (AclPermission s : serconds) {
            s.setChildren(findChildren(permissions,s.getId()));
        }
        return serconds;
    }



}